﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using Sunboxsoft.Common;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Edit
{
    public partial class UpdateBookingBillView : UserControl, IView
    {
        Guid _bookingBillId = Guid.Empty;
        Promise _promise = new Promise();

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存", OnSave_Click))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", OnCancel_Click));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise
                .Then(() =>
                {
                    SearchLookUpEditUtil.BindVStaffPosition(this.ctlSearchLookUpSalesManager, _promise, Domain.Constant.StaffPosts.SalesManager);
                })
                .Then(BindServiceProject)
                .Then(() =>
                {
                    if (_bookingBillId != Guid.Empty)
                    {
                        GetBookingBillDetail();
                    }
                })
                .Run(null);
        }
        public void Resume(ViewResumeArgs args)
        {
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("修改预约单");
        }
        #endregion

        #region Method
        public UpdateBookingBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.DateTimeValidation(txtBookDate, "预约到店时间"));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtRemark, "备注", true));
        }
        public UpdateBookingBillView(Guid bookingBillId)
            : this()
        {
            this._bookingBillId = bookingBillId;
        }
        /// <summary>
        /// 数据检查
        /// </summary>
        private bool ValidateData()
        {
            string message = null;
            if (GetListService().Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择服务项目！");
                return false;
            }
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 绑定服务项目
        /// </summary>
        private void BindServiceProject()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                PagedResult<WebRef.EServiceCategory> result = new Service.QueryService().QueryServiceCategoryPagedList(
                    ModuleContext.Current.BusinessId,
                    ModuleContext.Current.StationId,
                    Domain.Constant.CommonStatus.ALL,
                    0,
                    Domain.Constant.PageLimitAll);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        this.TreeListServiceProject.DataSource = result.Data.Items;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        /// <summary>
        /// 获取选中的服务项目
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EBookingService> GetListService()
        {
            List<WebRef.EBookingService> listService = new List<WebRef.EBookingService>();
            TreeListNodes list = this.TreeListServiceProject.Nodes;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].CheckState == CheckState.Checked)
                {
                    WebRef.EBookingService modelService = new WebRef.EBookingService();
                    modelService.ServiceCategoryId = new Guid(list[i].GetValue("Id").ToString());
                    listService.Add(modelService);
                }
            }
            return listService;
        }
        /// <summary>
        /// 选中已存的服务类别
        /// </summary>
        private void CheckedBookingService(List<WebRef.VBookingService> listService)
        {
            for (int i = 0; i < listService.Count; i++)
            {
                for (int j = 0; j < this.TreeListServiceProject.Nodes.Count; j++)
                {
                    if (listService[i].ServiceCategoryId.ToString() == this.TreeListServiceProject.Nodes[j].GetValue("Id").ToString())
                    {
                        this.TreeListServiceProject.Nodes[j].CheckState = CheckState.Checked;
                    }
                }
            }
        }
        /// <summary>
        /// 修改预约单
        /// </summary>
        private void UpdateBookingBill()
        {
            WebRef.EBookingBill entity = new WebRef.EBookingBill();
            entity.Id = _bookingBillId;
            entity.TargetDate = Convert.ToDateTime(this.txtBookDate.EditValue);
            entity.SalesManagerId = ctlSearchLookUpSalesManager.GetSelectedValue<WebRef.VStaffPosition>().GetStaffId();
            entity.Memo = this.txtRemark.Text.Trim();
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.UpdateService().UpdateBookingBill(_bookingBillId, entity, GetListService().ToArray());
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        /// <summary>
        /// 根据预约单ID获取其详细信息
        /// </summary>
        private void GetBookingBillDetail()
        {
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.BookingBillDetail> result = new Service.GetService().GetBookingBillDetail(_bookingBillId);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        this.txtCustomerName.Text = result.Data.BookingBill.CustomerName;
                        this.txtCustomerTel.Text = result.Data.BookingBill.CustomerTelephone;
                        this.txtCarLPN.Text = result.Data.BookingBill.AutomobileLPN;
                        this.txtCarVIN.Text = result.Data.BookingBill.AutomobileVIN;
                        this.txtBrand.Text = result.Data.Automobile.BrandName;
                        this.txtMaker.Text = result.Data.Automobile.MakerName;
                        this.txtSeries.Text = result.Data.Automobile.SeriesName;
                        this.txtModel.Text = result.Data.Automobile.ModelName;
                        CheckedBookingService(result.Data.ServiceList.ToList());
                        if (result.Data.BookingBill.SalesManagerId != null)
                        {
                            ctlSearchLookUpSalesManager.SelectVStaffPosition(new Guid(result.Data.BookingBill.SalesManagerId.ToString()));
                        }
                        this.txtBookDate.Text = result.Data.BookingBill.TargetDate.ToString();
                        this.txtRemark.Text = result.Data.BookingBill.Memo;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                    this.HideMask();
                }));
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 保存
        /// </summary>
        private void OnSave_Click(object sender, object e)
        {
            if (ValidateData())
            {
                UpdateBookingBill();
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        private void OnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, null);
        }
        /// <summary>
        /// 改变节点选中状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeListServiceProject_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            try
            {
                e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        #endregion
    }
}
